
package com.pekall.music.view;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Toast;

import com.pekall.music.model.LrcObject;

public final class ViewLrc extends View implements Runnable {

    private TextPaint paint;

    private int lrcWidth = 0;

    private int lrcSpeed = 200;

    private Thread ThreadKLOK = null;

    private int nState = 0;

    private boolean flag;

    private Context mContext;

    private boolean isExit;

    private List<LrcObject> lrc_map = new ArrayList<LrcObject>();

    private int mCurrentPosition;

    private int playingX;

    private Canvas lrc_backCanvas = null;

    private Canvas lrc_Canvas = null;

    private Bitmap mBitlrcBack = null;

    private Bitmap mBitlrc = null;

    private int lrcPanelWidth;

    private int lrcPanelHeight;

    public ViewLrc(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new TextPaint();
        mContext = context;
        ThreadKLOK = new Thread(this);
        ThreadKLOK.start();
        lrcPanelWidth = 480;
        lrcPanelHeight = 1024;

        mBitlrcBack = Bitmap.createBitmap(lrcPanelWidth, lrcPanelHeight, Config.ARGB_8888);
        mBitlrc = Bitmap.createBitmap(lrcPanelWidth, lrcPanelHeight, Config.ARGB_8888);
        lrc_backCanvas = new Canvas(mBitlrcBack);
        lrc_Canvas = new Canvas(mBitlrc);
    }

    private boolean isLrcExit(String path) {

        File file = new File(path);
        if (file.exists())
            return true;
        return false;
    }

    LrcObject val;

    @Override
    public void onDraw(Canvas canvas) {

        this.DrawImage(canvas, mBitlrcBack, 20, 30-(int)playingY, lrcPanelWidth, lrcPanelHeight, 0, 0);
        this.DrawImage(canvas, mBitlrc, 20, 30-(int)playingY, 4 * playingX, lrcPanelHeight, 0, 0);

    }

    private float playingY = 0;

    public void run() {
        while (true) {
            try {

                if (flag) {
                    if (nState == 1) {
                        if (playingX < lrcWidth) {
                            playingX++;
                            
                        } else {
                            playingX = 0;
                            playingY = playingY + 30;
                        }
                        Thread.sleep(lrcSpeed);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                Thread.currentThread().interrupt();
            }
            this.postInvalidate();
        }
    }

    private int playingLine = 0;

    private void findTheLrc() {
        playingLine = 0;

        for (int i = 0; i < lrc_map.size(); i++) {
            LrcObject val = (LrcObject) lrc_map.get(i);
            if (mCurrentPosition > (val.begintime + val.timeline)) {
                playingLine++;
            } else {
                break;
            }
        }

        for (int i = 0; i < lrc_map.size(); i++) {
            LrcObject val = (LrcObject) lrc_map.get(i);
            paint.setTextSize(20);
            Rect rect = new Rect();
            paint.getTextBounds(val.lrc, 0, val.lrc.length(), rect);
            float strwid = paint.measureText(val.lrc);

            lrcWidth = (int) strwid;

            lrcSpeed = val.timeline / lrcWidth;

            paint.setTextAlign(Paint.Align.CENTER);

            paint.setColor(Color.RED);
            lrc_backCanvas.drawText(val.lrc, 140, 30 + i * 30, paint);

            if (i == playingLine)
                paint.setColor(Color.GREEN);
            lrc_Canvas.drawText(val.lrc, 140, 30 + i * 30, paint);
        }

    }

    /**
     * x:屏幕上的x坐标 y:屏幕上的y坐标 w:要绘制的图片的宽度 h:要绘制的图片的高度 bx:图片上的x坐标 by:图片上的y坐标
     */
    public void DrawImage(Canvas canvas, Bitmap mBitmap, int x, int y, int w, int h, int bx, int by) {
        Rect src = new Rect();// 图片裁剪区域
        Rect dst = new Rect();// 屏幕裁剪区域
        src.left = bx;
        src.top = by;
        src.right = bx + w;
        src.bottom = by + h;

        dst.left = x;
        dst.top = y;
        dst.right = x + w;
        dst.bottom = y + h;

        canvas.drawBitmap(mBitmap, src, dst, paint);
        src = null;
        dst = null;
    }

    public void read(String file) {
        TreeMap<Integer, LrcObject> lrc_read = new TreeMap<Integer, LrcObject>();
        String data = "";

        try {
            File saveFile = new File(file);
            FileInputStream stream = new FileInputStream(saveFile);
            BufferedReader br = new BufferedReader(new InputStreamReader(stream, "utf8"));

            int i = 0;
            while ((data = br.readLine()) != null) {
                data = data.replace("[", "");
                data = data.replace("]", "@");

                String splistdata[] = data.split("@");
                String lrcContenet = splistdata[splistdata.length - 1];
                for (int j = 0; j < splistdata.length - 1; j++) {
                    String tmpstr = splistdata[j];
                    tmpstr = tmpstr.replace(":", ".");
                    tmpstr = tmpstr.replace(".", "@");
                    String timedata[] = tmpstr.split("@");

                    int m = Integer.parseInt(timedata[0]);// 分
                    int s = Integer.parseInt(timedata[1]);// 秒
                    int ms = Integer.parseInt(timedata[2]);// 毫秒
                    int currTime = (m * 60 + s) * 1000 + ms * 10;
                    LrcObject item1 = new LrcObject();

                    item1.begintime = currTime;
                    item1.lrc = lrcContenet;
                    lrc_read.put(currTime, item1);
                    i++;
                }
            }
            stream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 计算每一句歌词所需要的时间
        lrc_map.clear();
        Iterator<Integer> iterator = lrc_read.keySet().iterator();
        LrcObject oldval = null;
        int i = 0;
        StringBuffer sb = new StringBuffer();
        while (iterator.hasNext()) {
            Object ob = iterator.next();
            LrcObject val = (LrcObject) lrc_read.get(ob);
            if (oldval == null)
                oldval = val;
            else {
                LrcObject item1 = new LrcObject();
                item1 = oldval;
                item1.timeline = val.begintime - oldval.begintime;
                lrc_map.add(item1);
                sb.append(String.format("[%04d]-[%04d]-%s\n", item1.begintime, item1.timeline,
                        item1.lrc));
                i++;
                oldval = val;
            }
        }

    }

    /**
     * 设置当前播放歌曲
     * 
     * @param path
     */
    public void setlrcContent(String path) {

        isExit = isLrcExit(path);
        if (!isExit) {
            Toast.makeText(mContext, "文件不存在", Toast.LENGTH_LONG).show();
            LrcObject item = new LrcObject();
            item.lrc = "文件不存在，点击下载";
            lrc_map.add(item);
        } else {
            read(path);
        }
        lrcPanelWidth = 480;
        lrcPanelHeight = 30*lrc_map.size();
        // Log.d("--", lrc_map.toString());
    }

    /**
     * 设置当前播放位置
     * 
     * @param position
     */
    public void setlrcPosition(int position) {
        mCurrentPosition = position;
        findTheLrc();
    }

    public void Star() {
        flag = true;
        nState = 1;
    }

    public void Stop() {
        flag = false;
        nState = 0;
    }
}
